<template>
	<view>
		
		<view class="content">
		 
		        <!-- 聊天内容 -->
		        <scroll-view class="chat" scroll-y="true" scroll-with-animation="true" :scroll-into-view="scrollToView">
		            <view class="chat-main" :style="{paddingBottom:inputh+'px'}">
		                <view class="chat-ls">
							
							<view v-for="(message,i) in lobbyMessages.showMessages" :key="i">
								<view class="chat-time" v-show="i==0 || btwnSeconds(lobbyMessages.showMessages[i-1].time,lobbyMessages.showMessages[i].time) > 300">
									{{btwnDays(message.time,getNowTime())==0?message.time.substr(11,5):message.time.substr(0,16)}}
								</view>
								<view :class="['msg-m',message.id!=user.id?'msg-left':'msg-right']">
								    <image class="user-img" @tap="toPersonInfo(message.id)" :src="message.avatar"></image>
									<view class="content">
										<view class="nickname">
											<text :class="[message.id!=user.id?'left':'right']">{{message.nickname}}</text>
										</view>
										<view class="message">
								
											<!-- 文字 -->
										    <view class="msg-text" v-show="message.msgType=='text'">
												<rich-text class="rich-text" :nodes="replaceEmoji(message.content)"></rich-text>
											</view>
											<view class="message" v-show="message.msgType=='image'">
											    <!-- 图像 -->
											    <image :src="message.content" class="msg-img" @tap="showPic(message.content)" mode="widthFix"></image>
											</view>
										</view>
									</view>
								</view>
							</view>
		                    
		                </view>
		            </view>
		        </scroll-view>
		 
		    </view>
		
		
		
		
		
		
		<view class="footer" ref="footer" id="footer">
			<image @tap="selectImage()" class="icon" src="@/static/icon/photo.png"></image>
			<image @tap="turnEmojiShow()" class="icon" src="@/static/icon/emoji.png"></image>
			<view class="content-wrap">
				<textarea class="content" @keyup.enter="sendMessge()" v-model="textMsg" maxlength="-1" auto-height />
			</view>
			<view class="btn-wrap">
				<button class="btn" :disabled="disable" :class="{'disabled': disable}" @tap="sendMessge()">发送</button>
			</view>
		</view>
		
		
		
	
		<!-- emoji -->
		<scroll-view v-show="showEmoji" class="emoji-table" >
			<view class="btns">
				<text class="btn" @tap="lastEmojiPage()" v-show="emoji_start!=0">上一页</text>
				<text class="btn" @tap="nextEmojiPage()" v-show="emoji_start!=3">下一页</text>
				<text @tap="turnEmojiShow()" class="btn">关闭</text>
			</view>
			<image v-for="(emoji,pid) in emojis" :key="pid" class="emoji" mode="widthFix" :src="'/static/img/emoji/' + emoji.url"
				 @tap="addEmoji(emoji)">
		</scroll-view>
		
		<!-- 待发送的图片 -->
		<scroll-view v-show="showImage" class="image-table" >
			<view class="btns">
				<text @tap="imageEnsure()" class="btn">发送</text>
				<text @tap="imageCancel()" class="btn">取消</text>
			</view>
			<image class="selecting-image" :src="selecting_image"></image>
		</scroll-view>
	</view>
</template>

<script>
	import URL from '../../../api/url.js';
	import WebSocket from '@/common/websocket.js';
	import Util from '@/common/util.js';
	import dateUtil from 'util/date';
	import Emojis from '@/common/emojis.js';
	import {mapGetters,mapActions,mapMutations} from 'vuex';
	export default {
		data() {
			return {
				index:0,
				textMsg: '',
				texted:false, ///有没有发送过新的消息
				//表情定义
				showEmoji: false,
				emoji_start: 0,
				emojis:[],
				disable:true, //控制发送键能够按下
				
				inputh: '60',
				scrollToView: '',
				//关于发送图片
				showImage:false,
				selecting_image:'',//待发送的照片
				
				message_type:'',
				messages:[],
				
				messageIndex:0,//显示消息的索引
				messageSize:10,//默认一次性加载的大小
			}
		},
		computed:{
			...mapGetters(['user','sessions','lobbyMessages']),
		},
		watch: {
			//监听text，当他有值时发送按钮才可以点击
			textMsg(newVal) {
				if (newVal.trim() != '') {
					this.disable = false
				} else {
					this.disable = true
				}
			}
		},
		onReady() {
				//获取整个页面的高度，从而计算出页面可用的高度，因为使用了自定义的navbar所以this.pageHeight不是单纯的res.windowHeight。（ps: uview组件的navbar高度是固定的44px,不包括statusBarHeight）
				uni.getSystemInfo({
					success: (res) => {
						this.pageHeight = res.windowHeight - res.statusBarHeight - 44
					}
				})
		},
		onNavigationBarButtonTap: (button) => {
			if(button.index==0){
				uni.navigateTo({
					url:'../../space/zoom/zoom',
					animationType:'slide-in-right'
				})
			}
		},
		onLoad(options){
			///-1代表公共聊天室
			// if(options.index == -2){
				
			// }
			this.index = -2;
			this.message_type = 'lobby-message';
			this.setSessionIndex(-2);
			this.messages = this.lobbyMessages.messages;
			this.$store.state.lobbyMessages.unchecked = 0;
			this.emojis = Util.copySubList(Emojis,0,36);
			
			//如果消息的条数大于20的话
			if(this.lobbyMessages.messages.length>20){
				this.lobbyMessages.showMessages = this.lobbyMessages.messages.slice(this.lobbyMessages.messages.length-20,this.lobbyMessages.messages.length);
				this.messageIndex = this.lobbyMessages.messages.length - 20;
			}else{
				this.lobbyMessages.showMessages = this.lobbyMessages.messages; //否则
				this.messageIndex = 0;
			}
			
			setTimeout(()=>{
				uni.pageScrollTo({
					scrollTop: 99999999999,    //滚动到页面的目标位置（单位px）
					duration:0
				 });
			},200);
			
			
		},
		onUnload(){
			if(this.index != -2){
				this.reRangeSession(this.index);
			}
			this.setSessionIndex(-1);
			this.lobbyMessages.showMessages = []; //清除显示消息
		},
		// onPullDownRefresh() {
		// 		console.log('refresh');
		// 		setTimeout(function () {
		// 			uni.stopPullDownRefresh();
		// 		}, 1000);
		// 	},
		onPageScroll(e) {
			//#ifdef APP-PLUS
				if(e.scrollTop===0){
					setTimeout(()=>{
						uni.startPullDownRefresh({
							success() {
								if(this.messageIndex===0){
									uni.showToast({
										title:'已加载全部消息',
										icon:'none'
									})
								}
								else{
									if(this.messageIndex<20){
										this.lobbyMessages.showMessages = this.lobbyMessages.messages.slice(0,this.messageIndex).concat(this.lobbyMessages.showMessages);
										this.messageIndex = 0;
									}else{
										this.lobbyMessages.showMessages = this.lobbyMessages.messages.slice(this.messageIndex-20,this.messageIndex).concat(this.lobbyMessages.showMessages);
										this.messageIndex = this.messageIndex-20;
									}
								}
							},
							fail() {
								uni.showToast({
									title:'加载历史记录失败',
									icon:'error'
								})
							}
						})
					},100)
					setTimeout(()=>{
						uni.pageScrollTo({
							scrollTop: 10,    //滚动到页面的目标位置（单位px）
						});
					},100)
				}
			//#endif
		},
		 onPullDownRefresh() {
			if(this.messageIndex===0){
				uni.showToast({
					title:'已加载全部消息',
					icon:'none'
				})
			}
			else{
				if(this.messageIndex<20){
					this.lobbyMessages.showMessages = this.lobbyMessages.messages.slice(0,this.messageIndex).concat(this.lobbyMessages.showMessages);
					this.messageIndex = 0;
				}else{
					this.lobbyMessages.showMessages = this.lobbyMessages.messages.slice(this.messageIndex-20,this.messageIndex).concat(this.lobbyMessages.showMessages);
					this.messageIndex = this.messageIndex-20;
				}
			}
			
			uni.stopPullDownRefresh();
		},
		methods: {
			...mapMutations(['setSessionIndex']),
			...mapActions(['sendMessageOut','reRangeSession']),
			//主页
			toPersonInfo(id){
				uni.navigateTo({
					url:'../../other/search/info?id='+id+'&from=group',
					animationType:'slide-in-right'
				})
			},
			// 预览图片
			showPic(url) {
				uni.previewImage({
					indicator: 'none',
					current:url,
					urls:[url]
				});
			},
			//划到底部
			goPageBottom(){
				uni.pageScrollTo({
					scrollTop: 99999999999,    //滚动到页面的目标位置（单位px）
				});
			},
			//发送消息
			sendMessge(){
				//#ifdef APP-PLUS
					//去除回车
					for(let i=0;i<this.textMsg.length;){
						if(this.textMsg[i]=='\n'){
							this.textMsg=this.textMsg.substring(0,i)+this.textMsg.substring(i+1,this.textMsg.length);
							continue;
						}
						i++;
					}
				//#endif
				//#ifdef H5
					this.textMsg = this.textMsg.replaceAll('\n','');
				//#endif 
				if(this.textMsg==''||this.textMsg==' '||this.textMsg.length==0){
					return;
				}
				if(this.showEmoji){
					this.turnEmojiShow();
				}
				if(this.showImage){
					this.imageCancel();
				}
				if(this.textMsg.length>100){
					uni.showToast({
						title:'内容不能超过100个字哦~',
						icon:'none',
						mask:false,
						duration:1000
					})
				}else{
					let time = dateUtil.getTimeNow();
					//先发往服务器
					
					let outMessage = {
						type:this.message_type,
						message:{
							msgType: 'text',//消息类型
							time:time,
							content:this.textMsg,
							id:this.user.id,
							nickname:this.user.nickname,
							avatar:this.user.avatar
						}
					}
					
					WebSocket.sendMessage(outMessage);
					this.texted = true;
					this.textMsg = '';
					this.goPageBottom();
					// let success = WebSocket.sendMessage(outMessage);
					
					// if(success){
					// 	this.sendLobbyMessageOut(outMessage);
					// 	this.textMsg = '';
					// 	this.goPageBottom();
					// 	this.texted = true;
					// }
				}
			},
			//显示 关闭emoji
			turnEmojiShow() {
				if(this.showImage){
					this.imageCancel();
				}
				this.showEmoji = !this.showEmoji;
				this.emoji_start = 0;
			},
			//emoji翻页
			nextEmojiPage(){
				this.emoji_start ++;
				this.emojis = Util.copySubList(Emojis,this.emoji_start*36,36);
			},
			lastEmojiPage(){
				this.emoji_start --;
				this.emojis = Util.copySubList(Emojis,this.emoji_start*36,36);
			},
			//添加表情
			addEmoji(em) {
				this.textMsg += em.alt;
			},
			
			//选择照片
			async selectImage(){
				if(this.showEmoji){
					this.turnEmojiShow();
				}
				let that = this;
				await uni.chooseImage({
					count: 1,
					sizeType: ['original', 'compressed'],
					sourceType: ['album'],
					success: function(res) {
						that.selecting_image = res.tempFilePaths[0];
						that.showImage = true;
					}
				});
			},
			//取消发送照片
			imageCancel(){
				this.showImage = false;
				this.selecting_image = '';
			},
			//确认发送照片
			imageEnsure(){
				if(this.selecting_image==''){
					uni.showToast({
						title:'请选择图片哦~',
						icon:'none',
						mask:false,
						duration:1000
					})
				}else{
					
					//////////////////////////////////////////////////图片发送到服务器暂存/////////////////
					let that = this;
					uni.showLoading({
						title:'正在发送'
					})
					uni.uploadFile({
					     url: URL.getImageUrl()+'/upload',
					     filePath: that.selecting_image,
					     name: 'image',
					     formData: {
							 password:URL.getImagePassword(),
					         image: that.selecting_image
					     },
					     success: response => {
					         let res = JSON.parse(response.data);
					         if (res.code == 200) {
								 uni.hideLoading();
								//////////构造消息/////////////
								let time = dateUtil.getTimeNow();
								let url = URL.getImageUrl()+'/images/'+res.content.url;
								//先发往服务器
								let outMessage = {
									type:this.message_type,
									message:{
										msgType: 'image',//消息类型
										time:time,
										content:url,
										id:this.user.id,
										nickname:this.user.nickname,
										avatar:this.user.avatar
									}
								}
								
								WebSocket.sendMessage(outMessage);
								
								that.texted = true;
								that.imageCancel();
								that.goPageBottom();
								// let success = WebSocket.sendMessage(outMessage);
								
								// if(success){
								// 	let message ={
								// 		index:that.index,
								// 		content:res.message,
								// 		type:'image',
								// 		time: time
								// 	}
								// 	that.sendMessageOut(message);
								// 	that.goPageBottom();
								// 	that.texted = true;
								// 	that.imageCancel();
								// 	uni.hideLoading();
								// }
										
					         }
							 else{
							 	uni.hideLoading();
							 	uni.showToast({
							 		title:res.message,
							 		icon:'error'
							 	})
							 }
					     },
					     fail: err => {
							 uni.hideLoading();
					         uni.showToast({
					         	title:'图片上传失败~',
								icon:'error',
								duration:1000
					         })
					     }
					});
				}
			},
			replaceEmoji(text){
				return Util.replaceEmoji(text);
			},
			btwnSeconds(time1,time2){
				return dateUtil.TimeDifferenceSeconds(time1,time2);
			},
			btwnDays(time1,time2){
				return dateUtil.TimeDifference(time1,time2);
			},
			getNowTime(){
				return dateUtil.getTimeNow();
			}
		}
	}
</script>

<style scoped>
	 page {
	        height: 100%;
			background-color: rgba(244, 244, 244, 1);
	    }
		.text-show{
			/* padding: 10p;
			display: flex;
			align-items: center;
			word-wrap:break-word; */
			display: -webkit-box;
			overflow: hidden;
			text-overflow: ellipsis;
			word-wrap: break-word;
			white-space: normal !important;
			-webkit-box-orient: vertical;
		}
	.content{
		display: block;
	}
	.nickname{
		margin-left: 10px;
		text-align: right;
		display: flex;
	}
	.nickname .left{
	    text-align: right;
		float: right;
		margin-right: 10rpx;
		font-size: smaller;
	}
	.nickname .right{
	    text-align: right;
		margin-left: auto;
		margin-right: 20rpx;
		font-size: smaller;
	}
	 .user-img {
	     flex: none;
	     width: 100rpx;
	     height: 100rpx;
	     border-radius: 20rpx;
	 }
	 .chat-time {
	     font-size: 24rpx;
	     color: rgba(39, 40, 50, 0.3);
	     line-height: 34rpx;
	     padding: 10rpx 0rpx;
	     text-align: center;
	 }
	    .content {
	        height: 100%;
	        background-color: rgba(244, 244, 244, 1);
	    }
	 
	 .chat-main {
	     padding-left: 32rpx;
	     padding-right: 32rpx;
	     padding-top: 20rpx;
	     // padding-bottom: 120rpx;  //获取动态高度
	     display: flex;
	     flex-direction: column;
	 }
	 .message {
	     flex: none;
	     max-width: 480rpx;
	 }
	 .msg-text {
	     font-size: 32rpx;
	     color: rgba(39, 40, 50, 1);
	     line-height: 44rpx;
	     padding: 18rpx 24rpx;
		 
	 }
	 
	  
	    
	 	 
	.msg-left .msg-text {
		flex-direction: row;
	    margin-left: 16rpx;
	    background-color: #fff;
	    border-radius: 0rpx 20rpx 20rpx 20rpx;
	}
	
	.msg-left .msg-img {
		flex-direction: row;
	    margin-left: 16rpx;
	}
	 .msg-right{
		 flex-direction: row-reverse;
	 }		 
	 .msg-right .msg-text {
		 flex-direction: row-reverse;
	     margin-right: 16rpx;
	     background-color: rgba(85, 170, 255, 0.8);
	     border-radius: 20rpx 0rpx 20rpx 20rpx;
	 }	 	 
	 .msg-right .msg-img {
		 flex-direction: row-reverse;
	     margin-right: 16rpx;
	 }
	 
	.chat {
	    height: 100%;
	}
	.chat-ls .msg-m {
	   display: flex;
	   padding: 20rpx 0;	 	   
	}   
	.chat-ls .msg-img {
	    max-width: 400rpx;
	    border-radius: 20rpx;
	}	
	
	
	.emoji-table{
		   /*开启弹性布局*/
		display:flex;
		    /*wrap：换行，第一行在上方。*/
		flex-wrap:wrap;
		    /*居中对齐 每个项目两侧的间隔相等*/
		/* justify-content:space-around; */
		  /*或者使用 两端对齐，项目之间的间隔都相等。*/
		justify-content:space-between;
		max-width: 500rpx;
		max-height: 300rpx;
		position: fixed;
		z-index: 10;
		background-color: #f8fff2;
		padding: 5rpx;
		border-radius: 10rpx;
		bottom: 100rpx;
		left: 130rpx;
	}
	.btns{
		display: flex;
	}
	.btn{
		background-color: #55aaff;
		color: white;
		padding: 5rpx;
		font-size: small;
		margin-left: 10rpx;
		border-radius: 10rpx;
	}

	.emoji{
		width: 50rpx;
		height: 50rpx;
		margin: 2rpx;
	}
	.icon{
		width: 80rpx;
		height: 70rpx;
		margin-left: 10rpx;
		margin-top: auto;
		margin-bottom: 14rpx;
	}
	.selecting-image{
		width: 500rpx;
		height: 600rpx;
	}
	.image-table{
		   /*开启弹性布局*/
		display:flex;
		    /*wrap：换行，第一行在上方。*/
		flex-wrap:wrap;
		    /*居中对齐 每个项目两侧的间隔相等*/
		/* justify-content:space-around; */
		  /*或者使用 两端对齐，项目之间的间隔都相等。*/
		justify-content:space-between;
		max-width: 400rpx;
		max-height: 500rpx;
		position: fixed;
		z-index: 10;
		background-color: #f8fff2;
		padding: 5rpx;
		border-radius: 10rpx;
		bottom: 100rpx;
		left: 130rpx;
	}
	
		.footer {
			width: 100%;
			background-color: #E9EDF4;
			display: flex;
			position: fixed;
			bottom: 0;
		}
	
		.footer .content-wrap {
			width: 78%;
			margin-left: 2%;
		}
	
		.footer .content {
			width: 100%;
			box-sizing: border-box;
			margin: 14rpx 0;
			background-color: #FFFFFF;
			border-radius: 30rpx;
			padding: 16rpx;
			caret-color: #01B4FE;
			text-align: left;
		}
	
		.footer .btn-wrap {
			width: 18%;
			margin-right: 5%;
		}
	
		.footer .btn {
			width: 15%;
			height: 65rpx;
			font-size: 26rpx;
			margin-left: 2%;
			background-color: #01B4FE;
			color: #FFFFFF;
			position: fixed;
			bottom: 14rpx;
			border: 0;
			outline: none;
		}
	
		.footer .btn-wrap .disabled {
			background-color: #aae8f5;
		}
	
		/deep/ .uni-textarea-wrapper {
			max-height: 180rpx;
		}
		
</style>
